package com.matrix.common.handler;

import com.matrix.common.entity.CommonError;
import com.matrix.common.entity.Result;
import com.matrix.common.entity.ResultCode;
import com.matrix.common.entity.ResultCodeMsg;
import com.matrix.common.exception.BaseException;
import com.matrix.common.exception.CommonException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 自定义的公共异常处理器
 *      1.声明异常处理器
 *      2.对异常统一处理
 */
@ControllerAdvice
public class BaseExceptionHandler {

    @ExceptionHandler(value = BaseException.class)
    @ResponseBody
    public Result exceptionHandler(BaseException ex) {
        ResultCodeMsg resultCodeMsg = ex.getResultCodeMsg();
        return Result.error(resultCodeMsg);
    }


    @ExceptionHandler(value = CommonException.class)
    @ResponseBody
    public Result error(HttpServletRequest request, HttpServletResponse response,Exception e) {
        e.printStackTrace();
        if(e.getClass() == CommonException.class) {
            //类型转型
            CommonException ce = (CommonException) e;
            return Result.error(ce.getResultCodeMsg());
        }else{
            return Result.error(CommonError.SERVER_ERROR);
        }
    }
}
